package com.group4.xml;

/**
 * @author yaseminar
 *
 */

import java.io.StringReader;
import java.sql.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.group4.DAO.VideoDAO;
import com.group4.DB.Video;

public class XmlProcessor {

	public static String processXmlRequest(String inputXML) {

		String result = null;
		DocumentBuilder db;
		try {

			db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(inputXML));

			Document doc = db.parse(is);

			NodeList nList = doc.getElementsByTagName("method");

			Node nNode = nList.item(0);

			if (nNode.getNodeType() == Node.ELEMENT_NODE) {

				Element eElement = (Element) nNode;

				String methodName = eElement.getAttribute("name");

				String videoID = eElement.getElementsByTagName("ID").item(0)
						.getTextContent();

				if (methodName.equals("getVideoWithID")) {

					result = XmlResponse.returnVideoXML(Video
							.getVideoWithID(Integer.valueOf(videoID)));

				} else if (methodName.equals("addVideo")
						|| methodName.equals("updateVideo")) {
					VideoDAO video = new VideoDAO();

					video.setID(Integer.valueOf(videoID));
					video.setVideoName(eElement
							.getElementsByTagName("video_name").item(0)
							.getTextContent());
					video.setVideoUrl(eElement
							.getElementsByTagName("video_url").item(0)
							.getTextContent());
					video.setVideoDescription(eElement
							.getElementsByTagName("video_description").item(0)
							.getTextContent());
					video.setVideoUploaderID(Integer.valueOf(eElement
							.getElementsByTagName("video_uploaderId").item(0)
							.getTextContent()));
					video.setVideoUploadDateTime(Date.valueOf(eElement
							.getElementsByTagName("video_uploadDateTime")
							.item(0).getTextContent()));
					video.setVideoRate(Integer.valueOf(eElement
							.getElementsByTagName("video_rate").item(0)
							.getTextContent()));
					video.setVideoTag(eElement
							.getElementsByTagName("video_tag").item(0)
							.getTextContent());

					boolean isSuccess = false;
					if (methodName.equals("addVideo"))
						isSuccess = Video.addVideo(video);
					else
						isSuccess = Video.updateVideo(video);

					result = XmlResponse.prepareXMLResponse(isSuccess);
					
				} else if (methodName.equals("deleteVideo")) {
					result = XmlResponse.prepareXMLResponse(Video
							.deleteVideo(Integer.valueOf(videoID)));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
